package com.miniprogram.common.tools;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.google.common.io.Files;
import com.miniprogram.common.config.AliyunOSSProperty;
import com.miniprogram.common.enums.ClassificationEnum;
import com.miniprogram.common.enums.FolderEnum;
import com.miniprogram.common.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 阿里云操作类
 *
 * @author lin
 * @since 2020年01月05日
 */
@Slf4j
@Component
public class AliyunOSSUploader {

    private AliyunOSSProperty aliyunOSSProperty;

    private static final String HTTP = "http://";
    private static final String HTTPS = "https://";
    private static final String POINT = ".";
    private static final String SPRIT = "/";

    private OSSClient ossClient;

    public AliyunOSSUploader(AliyunOSSProperty aliyunOSSProperty) {
        this.aliyunOSSProperty = aliyunOSSProperty;
        ossClient = new OSSClient(aliyunOSSProperty.getEndpoint(), aliyunOSSProperty.getKey(), aliyunOSSProperty.getSecret());
    }

    public String put(HttpServletRequest request, MultipartFile file, FolderEnum folderEnum, boolean isHttps) throws IOException {
        return put(request, file, folderEnum, null, isHttps);
    }


    public String put(HttpServletRequest request, MultipartFile file, FolderEnum folderEnum, String key, boolean isHttps) throws IOException {
        String fileName = file.getOriginalFilename();
        if (fileName.lastIndexOf(".cach") > -1) {
            fileName = fileName.substring(0, fileName.lastIndexOf(".cach")) + ".png";
        }
        File tempFile = new File(request.getSession().getServletContext().getRealPath("/") + "tempImageUpload/", (null != key ? key : RandomUtil.GenerateDateTimeID()) + "." + Files.getFileExtension(fileName));
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        String path = put(tempFile, ClassificationEnum.YINGCHAO_CLOUD, folderEnum, tempFile.getName(), isHttps);
        // 上传后删除
        tempFile.delete();
        return path;
    }

    public String put(File file, ClassificationEnum classificationEnum, FolderEnum folderEnum, String key, boolean isHttps) throws IOException {
        //获取指定文件的输入流
        InputStream inputStream = new FileInputStream(file);
        //创建上传 Object 的 Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //必须设置
        objectMetadata.setContentLength(file.length());
        //上传 Object
        ossClient.putObject(aliyunOSSProperty.getBucket(), classificationEnum.getClassificationName() + folderEnum.getFolderName() + key, inputStream, objectMetadata);
        inputStream.close();
        return (isHttps ? HTTPS : HTTP) + aliyunOSSProperty.getSsl() + SPRIT + classificationEnum.getClassificationName() + folderEnum.getFolderName() + key;
    }

    /**
     * 上传
     */
    public String put(File file, FolderEnum folderEnum, String key) throws IOException {
        //获取指定文件的输入流
        InputStream inputStream = new FileInputStream(file);
        //创建上传 Object 的 Metadata
        ObjectMetadata objectMetadata = new ObjectMetadata();
        //必须设置
        objectMetadata.setContentLength(file.length());
        //上传 Object
        ossClient.putObject(aliyunOSSProperty.getBucket(), folderEnum.getFolderName() + key, inputStream, objectMetadata);
        inputStream.close();
        return HTTP + aliyunOSSProperty.getSsl() + SPRIT + folderEnum.getFolderName() + key;
    }


    /**
     * 删除
     */
    public void delete(String url) throws MalformedURLException {
        ossClient.deleteObject(aliyunOSSProperty.getBucket(), new URL(url).getPath().substring(1));
    }

    /**
     * 更新，先删除旧文件，再上传新文件
     */
    public void update(File file, FolderEnum folderEnum, String key, String oldUrl) throws Exception {
        delete(oldUrl);
        put(file, folderEnum, key);
    }

}
